package tech.xs.common.framework.init;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.SmartInitializingSingleton;
import org.springframework.stereotype.Component;
import tech.xs.common.framework.holder.SpringContextHolder;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.Map;

@Slf4j
@Component
public class RunInitExecute implements SmartInitializingSingleton {

    @Override
    public void afterSingletonsInstantiated() {
        Map<String, InitExecute> beansMap = SpringContextHolder.getBeansOfType(InitExecute.class);
        ArrayList<InitExecute> executeList = new ArrayList<>(beansMap.values());
        executeList.sort(Comparator.comparing(InitExecute::order));
        for (InitExecute execute : executeList) {
            try {
                log.info("[初始化执行器][开始]:" + execute.getClass().getName());
                execute.execute();
                log.info("[初始化执行器][结束]:" + execute.getClass().getName());
            } catch (Exception e) {
                log.error("[初始化执行器][异常]:", e);
                if (execute.isErrorStop()) {
                    System.exit(1);
                }
            }
        }
    }
}
